/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  Platform,
  StyleSheet,
  Text,
  View,
  Modal,
  Alert,
  Button,
  TextInput,
  TouchableHighlight,
  AsyncStorage,
  ToastAndroid,
} from 'react-native';
import { GiftedChat, Actions, Bubble, SystemMessage } from 'react-native-gifted-chat';
import SocketIOClient from 'socket.io-client';
import RNFetchBlob from 'react-native-fetch-blob';
import ImagePicker from 'react-native-image-crop-picker';
import FastImage from 'react-native-fast-image';
import Lightbox from 'react-native-lightbox';

console.disableYellowBox = true;

const USER_ID = '@userId';
const HOST =  `http://47.90.122.146:7001`; // `http://192.168.1.52:4000`;//
if (!window.location) {
  // App is running in simulator
  window.navigator.userAgent = 'ReactNative';
}

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      text: '',
      num: 0,
      selected: [], // 已选择图片数组
      messages: [],
      modalVisible: true,
      btnDisabled: false,
      userId: null,
      username: '略',
    };
    this.socket = SocketIOClient(HOST, {transports: ['websocket']});
    this.determineUser();
  }
  /**
   * 设置用户端唯一标识
   */
  determineUser() {
    AsyncStorage.getItem(USER_ID)
      .then((username) => {
        console.log('用户 ID:', username);
        this.socket.emit('userJoined', {username, }, (result)=>{
          console.log('用户事件,回调函数:', result);
          this.setState({
            text: username,
          });
        });
      })
      .catch((e) => alert(e));
  }
  // 发送消息
    onSend=(messages = [])=>{
    this.setState(previousState => ({
      messages: GiftedChat.append(previousState.messages, messages),
    }));
    this.socket.emit('message', messages, (result)=> {
      if(result==='success'){
        console.log(`发送消息:${JSON.stringify(messages)} ,状态: ${result}`);
        // 服务端收到消息后,更新消息状态
        // AuroraIController.updateMessage(Object.assign({}, message, {status: 'send_succeed'}));
      }
    });
  };
  /**
   * When the server sends a message to this.
   * 服务端发送消息,接收到
   */
  onReceivedMessage(messages) {
    const arr = messages.filter((item)=> {
      if(item.image){
        item.image = HOST+item.image;
      }
      return item.user._id!==this.state.userId;
    });
    this.setState(previousState => ({
      messages: GiftedChat.append(previousState.messages, arr),
    }));
  }
  componentWillMount() {
    this.socket.on('message', (messages)=> {this.onReceivedMessage(messages)});
  }
  renderActions = (props) => {
    const options = {
      '拍照': (props) => {
        ImagePicker.openCamera({
          compressImageMaxWidth: 800,
        }).then(image => {
          console.log(image);
          const obj = this.getData({image: image.path});
          this.onSendFile(image.path, {
            mime: image.mime,
            path: image.path,
            message: obj,
          });
          this.setState(previousState => ({
            messages: GiftedChat.append(previousState.messages, [obj]),
          }));
        });
      },
      '选择照片': (props) => {
        ImagePicker.openPicker({
          mediaType: 'photo',
          multiple: true,
          compressImageMaxWidth: 800,
        }).then(images => {
          const arr = images.map((item)=> {
            const obj = this.getData({image: item.path});
            this.onSendFile(item.path, {
              mime: item.mime,
              path: item.path,
              message: obj,
            });
            return obj;
          });
          this.setState(previousState => ({
            messages: GiftedChat.append(previousState.messages, arr),
          }));
        });
      },
      '选择视频': (props) => {
        ImagePicker.openPicker({
          cropping: false,
          mediaType: "video",
        }).then((video) => {
          ToastAndroid.show(`选择视频成功,共${Math.floor(video.size/1080/1080)}M`, ToastAndroid.SHORT);
          const obj = this.getData({video: video.path, text: '接收到新的视频'});
          this.onSendFile(video.path, {
            mime: video.mime,
            path: video.path,
            message: obj,
          });
        });
      },
      '取消': () => {
      },
    };
    return (
      <Actions
        { ...props }
        options={ options }
      />
    );
  };

  getData = (options)=> {
    return Object.assign({
      _id: new Date().getTime() + '' + Math.floor(Math.random()*1000),
      createdAt: new Date(),
      user: {
        _id: this.state.userId,
        name: this.state.username,
      },
    }, options);
  };

  onSendFile = (uri, options={})=> {
    console.log(`开始读取文件:${uri}`);
    /*RNFetchBlob.fs.readStream(uri, 'ascii')
      .then((stream) => {
        let data = [];
        stream.open();
        stream.onData((chunk) => {
          data.push(chunk);
        });
        stream.onEnd(() => {
          console.log(`已读取文件结束:${data.length}`);
          this.socket.emit('file', Object.assign({
            data: data,
          },options), (result)=> {
            ToastAndroid.show(`文件上传成功,返回 uri: ${result}`, ToastAndroid.SHORT);
            console.log(`发送文件,服务端返回:${result}`);
          });
        });
      });*/

    RNFetchBlob.fetch('POST', `${HOST}/upload`, {
      'Content-Type' : 'multipart/form-data',
    }, [
      { name : 'avatar-foo', filename : 'avatar-foo.jpg', type:options.mime, data: RNFetchBlob.wrap(uri)},
    ])
      .uploadProgress((written, total) => {
        console.log('uploaded', written / total)
      })
      .progress((received, total) => {
        console.log('progress', received / total)
      })
      .then((resp) => {
        return resp.json();
      })
      .then((result)=> {
      console.log(result.url);
      options.message.image = result.url;
      this.socket.emit('message', [options.message], (result)=> {
        ToastAndroid.show(`文件上传成功,返回 uri: ${result}`, ToastAndroid.SHORT);
      });
    })
      .catch((err) => {
        ToastAndroid.show(`文件 发送失败:${err}`, ToastAndroid.SHORT);
      })

  };

  onButtonPress=()=> {
    console.log('点击按钮');
    this.setState({
      btnDisabled: true,
    });
    const params = {
      username: this.state.text,
      btnDisabled: false,
    };
    this.socket.emit('userJoined', {
      username: this.state.text,
    }, (result)=>{
      console.log('用户事件,回调函数:', result);
      if (result.result==='success') {
        params.userId = result.userId;
        params.modalVisible = false;
        AsyncStorage.setItem(USER_ID, params.username);
      }else{
        Alert.alert('该用户已存在');
        params.modalVisible = true;
      }
      this.setState(params);
    });
  };

 renderImage(){
     //currentMessage
     let url = this.currentMessage && this.currentMessage.image;
     if(!url){
       url = '';
     }
     console.log(url);
     return (
       <View style={styles.container}>
         <Lightbox
           activeProps={{
             style: styles.imageActive,
           }}
           {...this.lightboxProps}
         >
           <FastImage
             {...this.imageProps}
             style={styles.image}
             source={{
               uri: url,
               priority: FastImage.priority.normal,
             }}
             resizeMode={FastImage.resizeMode.contain}
           />
         </Lightbox>
       </View>
     );
}
  render() {
    return (
      <View style={ styles.container }>
        <Modal
          animationType={"slide"}
          transparent={false}
          visible={this.state.modalVisible}
          onRequestClose={this.onButtonPress}>
          <View style={ styles.container }>
            <TextInput
              style={{height: 40, borderColor: 'gray', borderWidth: 1}}
              autoFocus={true}
              placeholder="请输入用户名"
              onChangeText={(text) => this.setState({text})}
              value={this.state.text}
            />
              <Button
                onPress={this.onButtonPress}
                disabled={this.state.btnDisabled}
                title="确定"
                accessibilityLabel="确定"
              />
          </View>

        </Modal>
        <GiftedChat
          messages={ this.state.messages }
          renderActions={ this.renderActions }
          onSend={ messages => this.onSend(messages) }
          locale="zh_TW"
          showAvatarForEveryMessage={true}
          renderMessageImage={this.renderImage}
          user={{
            _id: this.state.userId,
            name: this.state.username,
          }}
        />
      </View>
    );
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  contentWrapper:{
    flex: 1,
    backgroundColor: '#F6AE2D',
  },
  content: {
    height: 50,
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    flexWrap: 'wrap',
    backgroundColor: '#F6AE2D',
  },
  text: {
    fontSize: 16,
    alignItems: 'center',
    color: '#fff',
  },
  imageModelSure: {
    fontSize:16,
    color: '#fff',
  },
  bold: {
    fontWeight: 'bold',
  },
  info: {
    fontSize: 12,
  },
  image: {
    width: 150,
    height: 100,
    borderRadius: 13,
    margin: 3,
    resizeMode: 'cover',
  },
  imageActive: {
    flex: 1,
    resizeMode: 'contain',
  },
});
